<?php
/**
 * 会员中心——账户概览
 *
 *
 *
 * * @好商城 (c) 2015-2018 33HAO Inc. (http://www.33hao.com)
 * @license    http://www.33 hao.c om
 * @link       交流群号：138182377
 * @since      好商城提供技术支持 授权请购买shopnc授权
 */



defined('In33hao') or exit('Access Invalid!');

class storeControl extends BaseMemberControl{
    public function __construct() {
        parent::__construct();
        /**
         * 读取语言包
         */
    }
    /**
     * 我的店铺设置
     */
    public function store_settingOp() {
        // 检测是否购买了自助开店
        $model_class = Model('goods_class');
        $condition['isshow'] = 0;
        $condition['is_open'] = 1;
        $goods_class = $model_class->getGoodsClassList($condition,'gc_id');
        $gc_idstr = '';
        foreach($goods_class as $k => $v){
            $gc_idstr .= $v['gc_id'].',';
        }
        $where['gc_id'] = array('in',trim($gc_idstr,','));
        $where['buyer_id'] = $_SESSION['member_id'];
        $fields = 'MAX(goods_price) AS nc_max,order_id';
        $order_goods_info = Model('order_goods')->field($fields)->where($where)->find();
        if(!$order_goods_info['nc_max']){
            showMessage('您还没有购买自助开店的资格', '', 'html', 'error');
        }
        if (chksubmit())
        {
            $memberName = $_SESSION['member_name'];
            $memberPasswd = (string) $_POST['member_passwd'];
            $memberletters = $_POST['store_letters'];
            if (strlen($memberName) < 3 || strlen($memberName) > 15
                || strlen($_POST['seller_name']) < 3 || strlen($_POST['seller_name']) > 15)
                showMessage('账号名称必须是3~15位', '', 'html', 'error');

            if (strlen($memberPasswd) < 6)
                showMessage('登录密码不能短于6位', '', 'html', 'error');

            if (!$this->checkMemberName($memberName))
                showMessage('店主账号已被占用', '', 'html', 'error');

            if (!$this->checkSellerName($_POST['seller_name']))
                showMessage('店主卖家账号名称已被其它店铺占用', '', 'html', 'error');

            if(!$this->CheckChars($memberletters)){
                showMessage('店铺首字母填写错误', '', 'html', 'error');
            }

            $storeModel = model('store');

            $saveArray = array();
            $saveArray['store_name'] = $_POST['store_name'];
            $saveArray['store_class'] = 0;
            $saveArray['store_letters'] = $_POST['store_letters'];
            $saveArray['member_id'] = $_SESSION['member_id'];
            $saveArray['member_name'] = $memberName;
            $saveArray['seller_name'] = $_POST['seller_name'];
            $saveArray['bind_all_gc'] = 1;
            $saveArray['store_state'] = 1;
            $saveArray['store_time'] = time();
            $saveArray['is_own_shop'] = 0;
            //判断开店类型
            $settings = Model('setting')->getListSetting();
            if ($order_goods_info['nc_max'] == $settings['fx_st_tc_one']) {
                $saveArray['type'] = 1;
            }
            if ($order_goods_info['nc_max'] == $settings['fx_st_tc_two']) {
                $saveArray['type'] = 2;
            }
            if ($order_goods_info['nc_max'] == $settings['fx_st_tc_three']) {
                $saveArray['type'] = 3;
            }
            if ($order_goods_info['nc_max'] == $settings['fx_st_tc_four']) {
                $saveArray['type'] = 4;
            }
            $storeId = $storeModel->addStore($saveArray);

            model('seller')->addSeller(array(
                'seller_name' => $_POST['seller_name'],
                'member_id' => $_SESSION['member_id'],
                'store_id' => $storeId,
                'seller_group_id' => 0,
                'is_admin' => 1,
            ));

            model('store_joinin')->save(array(
                'seller_name' => $_POST['seller_name'],
                'store_name'  => $_POST['store_name'],
                'member_name' => $memberName,
                'member_id' => $_SESSION['member_id'],
                'joinin_state' => 40,
                'company_province_id' => 0,
                'sc_bail' => 0,
                'joinin_year' => 1,
            ));

            // 添加相册默认
            $album_model = Model('album');
            $album_arr = array();
            $album_arr['aclass_name'] = '默认相册';
            $album_arr['store_id'] = $storeId;
            $album_arr['aclass_des'] = '';
            $album_arr['aclass_sort'] = '255';
            $album_arr['aclass_cover'] = '';
            $album_arr['upload_time'] = time();
            $album_arr['is_default'] = '1';
            $album_model->addClass($album_arr);

            //插入店铺扩展表
            $model = Model();
            $model->table('store_extend')->insert(array('store_id'=>$storeId));

            // 删除自营店id缓存
            Model('store')->dropCachedOwnShopIds();

            //处理自助开店后续操作
            dealOpenStore($_SESSION['member_id'],$order_goods_info['order_id']);

            $this->log("新增外驻店铺: {$saveArray['store_name']}");
            showMessage('操作成功','/index.php?act=member&op=home');
            return;
        }
        $memberName = $_SESSION['member_name'];
        // 判断是否已添加店铺
        $count = (int) Model('store_joinin')->getStoreJoininCount(array(
            'member_name' => $memberName,
        ));
        if ($count > 0){
            showMessage('您已经设置了店铺,请前往商家管理中心进行管理', '', 'html', 'error');
        }

        Tpl::showpage("store_add");
    }

    public function check_seller_nameOp()
    {
        echo json_encode($this->checkSellerName($_GET['seller_name'], $_GET['id']));
        exit;
    }

    private function checkSellerName($sellerName, $storeId = 0)
    {
        // 判断store_joinin是否存在记录
        $count = (int) Model('store_joinin')->getStoreJoininCount(array(
            'seller_name' => $sellerName,
        ));
        if ($count > 0)
            return false;

        $seller = Model('seller')->getSellerInfo(array(
            'seller_name' => $sellerName,
        ));

        if (empty($seller))
            return true;

        if (!$storeId)
            return false;

        if ($storeId == $seller['store_id'] && $seller['seller_group_id'] == 0 && $seller['is_admin'] == 1)
            return true;

        return false;
    }

    public function check_member_nameOp()
    {
        echo json_encode($this->checkMemberName($_GET['member_name']));
        exit;
    }

    //检测是否为字母
    private function CheckChars($str){
        if(empty($str))return false;
        return  (bool)preg_match("/^([a-z\s]*)$/isU",$str);
    }

    private function checkMemberName($memberName)
    {
        // 判断store_joinin是否存在记录
        $count = (int) Model('store_joinin')->getStoreJoininCount(array(
            'member_name' => $memberName,
        ));
        if ($count > 0)
            return false;
        return 1;
    }

    /**
     * 记录系统日志
     *
     * @param $lang 日志语言包
     * @param $state 1成功0失败null不出现成功失败提示
     * @param $admin_name
     * @param $admin_id
     */
    protected final function log($lang = '', $state = 1, $admin_name = '', $admin_id = 0) {
        if (!C('sys_log') || !is_string($lang)) return;
        if ($admin_name == ''){
            $admin = unserialize(decrypt(cookie('sys_key'),MD5_KEY));
            $admin_name = $admin['name'];
            $admin_id = $admin['id'];
        }
        $data = array();
        if (is_null($state)){
            $state = null;
        }else{
            $state = $state ? '' : L('nc_fail');
        }
        $data['content']    = $lang.$state;
        $data['admin_name'] = $admin_name;
        $data['createtime'] = TIMESTAMP;
        $data['admin_id']   = $admin_id;
        $data['ip']         = getIp();
        $data['url']        = $_REQUEST['act'].'&'.$_REQUEST['op'];
        return Model('admin_log')->insert($data);
    }
}
